//
//  DevSettingModel.m
//  RuiHeApp
//
//  Created by Jun on 2022/11/30.
//

#import "DevSettingModel.h"

@implementation DevSettingModel

+ (NSDictionary *)modelContainerPropertyGenericClass {
     return @{@"selectList" : [DevSettingOptionModel class],
              @"properList" : [DevSettingModel class]
     };
 }


- (void)setData:(NSDictionary *)data{
    _data = data;
    if(_data == nil)return;
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in self.keys) {
        NSDictionary *dic = _data[key];
        DevSettingModel *model = [DevSettingModel yy_modelWithDictionary:dic];
        model.field = key;
        [array addObject:model];
    }
    self.dataList = array;
    _data = nil;
}


- (void)setProperties:(id)properties{
    _properties = properties;
    if ([_properties isKindOfClass:[NSString class]] || _properties==nil) {
        return;
    }
    NSDictionary *properties_dic = (NSDictionary *)_properties;
    NSMutableArray *array = [NSMutableArray array];
    //NSLog(@"self.keys ==== %@",[self.keys debugDescription]);
    for (NSString *key in self.keys) {
        NSDictionary *dic = properties_dic[key];
        DevSettingModel *model = [DevSettingModel yy_modelWithDictionary:dic];
        model.field = key;
        [array addObject:model];
    }
    self.properList = array;
    _properties = nil;
}

- (void)setType:(NSString *)type{
    _type = type;
    if ([_type isEqualToString:@"select"]) {
        TextInputModel *inputModel = [[TextInputModel alloc] init];
        inputModel.titile = ValidStr(_nickname)?_nickname:@"";
        inputModel.content = @"";
        inputModel.t_color = @"#333333";
        inputModel.placeholder = [NSString stringWithFormat:@"-- %@ --",@"Select an option".rh_localized];
        inputModel.optionList = self.selectList;
        inputModel.inputType = TextInputChoiceType;
        self.inputModel = inputModel;
    }
}

- (void)setNickname:(NSString *)nickname{
    _nickname = nickname;
    if (self.inputModel) {
        self.inputModel.titile = _nickname;
    }
}

- (void)setSelectList:(NSArray<DevSettingOptionModel *> *)selectList{
    _selectList = selectList;
    if (self.inputModel) {
        self.inputModel.optionList = _selectList;
    }
}


//切换日月元的工作模式
-(void)changeRYYWorkMode:(NSInteger)workMode
{
    NSArray *workModeJsonFiles = @[@"setting_ao_ryy_pcs_SelfUseMode",
                                   @"setting_ao_ryy_pcs_BackupMode",
                                   @"setting_ao_ryy_pcs_LowCostACChargeModel",
                                   @"setting_ao_ryy_pcs_OffGridMode",
                                   @"setting_ao_ryy_pcs_SelfDefineMode"
                                    ];
    NSString *path = [[NSBundle mainBundle] pathForResource:workModeJsonFiles[workMode] ofType:@"json"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    
    NSArray *dataArr = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    self.properList = [NSArray yy_modelArrayWithClass:[DevSettingModel class] json:dataArr];
    [self.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull child_model, NSUInteger idx, BOOL * _Nonnull stop) {
        if([child_model.type isEqualToString:@"select"] && (child_model.content.length > 0)){
            child_model.inputModel.content = child_model.content;
            for (DevSettingOptionModel *select_model in child_model.inputModel.optionList) {
                if([child_model.content integerValue] == select_model.textValue){
                    child_model.inputModel.content = select_model.text;
                    child_model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];
                }
            }
        }
    }];

}

//切换日月元的(Self Defined Mode)工作模式下的 Machine Model
-(void)changeRYYMachineModel:(NSInteger)MachineModel
{
    NSArray *workModeJsonFiles = @[@"setting_ao_ryy_pcs_GridTiedWithBackup",
                                   @"setting_ao_ryy_pcs_OffGird_Ⅰ",
                                   @"setting_ao_ryy_pcs_OffGird_ⅠI",
                                   @"setting_ao_ryy_pcs_OffGird_ⅠII",
                                   @"setting_ao_ryy_pcs_GridTied",
                                   @"setting_ao_ryy_pcs_TimeOfUse"
                                    ];
    NSString *path = [[NSBundle mainBundle] pathForResource:workModeJsonFiles[MachineModel] ofType:@"json"];
    NSLog(@"---->加载的文件名:%@",workModeJsonFiles[MachineModel]);
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    
    NSArray *dataArr = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    self.properList = [NSArray yy_modelArrayWithClass:[DevSettingModel class] json:dataArr];
    [self.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull child_model, NSUInteger idx, BOOL * _Nonnull stop) {
        if([child_model.type isEqualToString:@"select"] && (child_model.content.length > 0)){
            child_model.inputModel.content = child_model.content;
            for (DevSettingOptionModel *select_model in child_model.inputModel.optionList) {
                if([child_model.content integerValue] == select_model.textValue){
                    child_model.inputModel.content = select_model.text;
                    child_model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];
                }
            }
        }
    }];

}

//切换日月元的 光伏能量使用优先级
-(void)changeRYYPvPriority:(NSInteger)index
{
    //P_PvDisFeNormEn   P_PvDisLoNormEn
    
        [self.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if([obj.field isEqualToString:@"Inv1_PvDisFeNormEn"]||[obj.field isEqualToString:@"Inv1_PvDisLoNormEn"]){
                if(index == 0){
                    obj.disable = YES;
                    obj.content = @"0";
                }else{
                    obj.disable = NO;
                    obj.content = @"0";
                }
                
            }
            
        }];
   
}

//切换日月元的 充电优先级  Charger source priority
-(void)changeRYYChargePriority:(NSInteger)index
{
    //P_BatChEn  P_ACBatChEn
    __block DevSettingModel *pvModel;
    __block DevSettingModel *acModel;
    [self.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj.field isEqualToString:@"Inv1_BatChEn"]){
            pvModel = obj;
        }
        if([obj.field isEqualToString:@"Inv1_ACBatChEn"]){
            acModel = obj;
        }
    }];
    if(index == 0){
        pvModel.disable = YES;
        pvModel.content = @"1";
        acModel.disable = YES;
        acModel.content = @"1";
    }else if (index == 1){
        pvModel.disable = YES;
        pvModel.content = @"1";
        acModel.disable = YES;
        acModel.content = @"0";
    }else if (index == 2){
        pvModel.disable = YES;
        pvModel.content = @"0";
        acModel.disable = YES;
        acModel.content = @"0";
    }
}


//切换日月元的 光伏能量使用优先级  PV Energy Usage Priority
-(void)changeRYYPvUsagePriority:(NSInteger)index
{
    //P_PvDisFeNormEn  P_PvDisLoNormEn
    __block DevSettingModel *pvDischgGridModel;
    __block DevSettingModel *pvDischgLoadModel;
    [self.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj.field isEqualToString:@"Inv1_PvDisFeNormEn"]){
            pvDischgGridModel = obj;
        }
        if([obj.field isEqualToString:@"Inv1_PvDisLoNormEn"]){
            pvDischgLoadModel = obj;
        }
    }];
    if(index == 0){
        pvDischgGridModel.disable = YES;
        pvDischgGridModel.content = @"0";
        pvDischgLoadModel.disable = YES;
        pvDischgLoadModel.content = @"0";
    }else {
        pvDischgGridModel.disable = NO;
        pvDischgGridModel.content = @"0";
        pvDischgLoadModel.disable = NO;
        pvDischgLoadModel.content = @"0";
    }
}


//日月元  进入页面设备处于self define mode 时,先根据machine model的值加载对应的json文件,再读取默认值
-(void)handleRYYWorkModeWithDevInfo:(NSDictionary*)dic
{
    NSInteger machineModel = [dic[@"Inv1_MachineModel"] integerValue];
    __block NSInteger machineIndex = -1;
    //对应的下标
    [self.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj.field isEqualToString:@"Inv1_MachineModel"]){
            [obj.selectList enumerateObjectsUsingBlock:^(DevSettingOptionModel * _Nonnull optModel, NSUInteger idx, BOOL * _Nonnull stop) {
                if(optModel.textValue == machineModel){
                    machineIndex = idx;
                }
            }];
        }
    }];
    if(machineIndex >=0){
       
        //Machine Model == Grid-Tied With Backup 时 根据PV Energy Usage Priority的值
        //在读取的时候,如果没有P_PVEnerSuPri(PV Energy Usage Priority)这个选项,就不做如下操作
        if(machineIndex == 0){
           NSInteger pvEnUsagePri = [dic[@"Inv1_PVEnerSuPri"] integerValue];
           __block DevSettingModel *model;
            [self.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if([obj.field isEqualToString:@"Inv1_PVEnerSuPri"]){
                    model = obj;
                    *stop = YES;
                }
            }];
            //禁用的情况下就不操作
            if(model&&model.disable == NO){
                [self changeRYYPvPriority:pvEnUsagePri];
            }
            
        }
        //读取时对  Off-Gird Ⅱ 的处理  ,如果 P_PVEnerSuPri 是0 (也就是 Battery-Load-Grid ),那么将P_PVEnerSuPri的值改为 152
        if((machineModel == 150) && ([dic[@"Inv1_PVEnerSuPri"] integerValue] == 0)){
            [self changeRYYMachineModel:2];
        }else if((machineModel == 77) && ([dic[@"Inv1_PVEnerSuPri"] integerValue] == 3)){
            //P_MachineModel = 77 并且 P_PVEnerSuPri = 3的时候, 要将 77(Grid-Tied With Backup) 改成显示 78(Time of Use)
            [self changeRYYMachineModel:5];
        }else{
            [self changeRYYMachineModel:machineIndex];
        }
        
    }

}

//加载日月元 self define mode 下的数据
-(void)loadRYYWorkModeDataWithDevInfo:(NSDictionary*)dic
{
    //Charger source priority的值 根据PV Charge Enable和AC Charge Enable来取
    //P_BatChEn  P_ACBatChEn
    NSInteger p_Bat   = [dic[@"Inv1_BatChEn"] integerValue];
    NSInteger p_acBat = [dic[@"Inv1_ACBatChEn"] integerValue];
    NSInteger chSourcePri = 0;
    if(p_Bat == 1 && p_acBat == 1){
        chSourcePri = 0;
    }else if(p_Bat == 1 && p_acBat == 0){
        chSourcePri = 1;
    }else if(p_Bat == 0 && p_acBat == 0){
        chSourcePri = 2;
    }
    
    //根据 PV Energy Usage Priority 的值 修改 P_PvDisFeLossEn 等选项
    NSInteger pvChgPri = [dic[@"Inv1_PVEnerSuPri"] integerValue];
    __block DevSettingModel *model;
    [self.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj.field isEqualToString:@"Inv1_PVEnerSuPri"]){
            model = obj;
        }
    }];
    //如果machineMode是禁用的情况下,就不做这个操作
    if(model && model.disable == NO){
        [self changeRYYPvUsagePriority:pvChgPri];
    }
    
    
    
    //GridTied Enable  以下 ,没有用的都赋值一次
    for (DevSettingModel *child_model in self.properList) {
        //工作模式不加载,不然切换工作模式就无效了
        if([child_model.field isEqualToString:@"Inv1_WorkModeSet"])continue;
        
        //日月元 Inverter参数设置  self define mode 以外的其他四种模式不加载默认值
        if(child_model.disable) continue;
        
  
        //self define mode 时,读取时对  Off-Gird Ⅱ 的处理  ,如果 P_PVEnerSuPri 是0 (也就是 Battery-Load-Grid,这里就不赋值了,直接用json文件里的
        if([child_model.field isEqualToString:@"Inv1_MachineModel"]){
            if([dic[@"Inv1_MachineModel"] integerValue] == 150 && [dic[@"Inv1_PVEnerSuPri"] integerValue] == 0 ){
                continue;
            }
            if(([dic[@"Inv1_MachineModel"] integerValue] == 77) && ([dic[@"Inv1_PVEnerSuPri"] integerValue] == 3)){
                //P_MachineModel = 77 并且 P_PVEnerSuPri = 3的时候, 要将 77(Grid-Tied With Backup) 改成显示 78(Time of Use) ,所以这里也不赋值
                continue;
            }
        }
        
            
            
        NSNumber *number = dic[child_model.field];
        if (child_model.ratio) {
            number = @([dic[child_model.field] integerValue]*[child_model.ratio doubleValue]);
        }
        //开关类型,值超过1的情况
        if([child_model.type isEqualToString:@"switch"]&& [number integerValue]>1){
            number = (0);
        }
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        formatter.numberStyle = NSNumberFormatterDecimalStyle;
        //formatter.maximumFractionDigits = 1;
        [formatter setRoundingMode: NSNumberFormatterRoundDown];
        child_model.content = [[formatter stringFromNumber:number] stringByReplacingOccurrencesOfString:@"," withString:@""];


        if([child_model.type isEqualToString:@"select"]){
            child_model.inputModel.content = child_model.content;
            for (DevSettingOptionModel *select_model in child_model.inputModel.optionList) {
                //self define mode 时,读取时对  Off-Gird Ⅱ 的处理  ,如果 P_PVEnerSuPri 是0 (也就是 Battery-Load-Grid,这里就不赋值了,直接用json文件里的
                if([child_model.field isEqualToString:@"Inv1_MachineModel"]){
                    if([dic[@"Inv1_MachineModel"] integerValue] == 150 && [dic[@"Inv1_PVEnerSuPri"] integerValue] == 0){
                        continue;
                    }
                    
                    if(([dic[@"Inv1_MachineModel"] integerValue] == 77) && ([dic[@"Inv1_PVEnerSuPri"] integerValue] == 3)){
                        //P_MachineModel = 77 并且 P_PVEnerSuPri = 3的时候, 要将 77(Grid-Tied With Backup) 改成显示 78(Time of Use) ,所以这里也不赋值
                        continue;
                    }
                }
                
                
                
                if([child_model.content integerValue] == select_model.textValue){
                    child_model.inputModel.content = select_model.text;
                    child_model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];
                }
            }
            
            //Charger source priority的值 根据PV Charge Enable和AC Charge Enable来取
            if([child_model.field isEqualToString:@"Inv1_chgPri"]&&chSourcePri<child_model.inputModel.optionList.count){
                    DevSettingOptionModel *select_model = child_model.inputModel.optionList[chSourcePri];
                    child_model.inputModel.content = select_model.text;
                    child_model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];
            }
 
        }
    }
}


//加载某一部分值,在设备处于self define mode模式下,手动切换了其他的模式再切回来,再选择了machine model的情况,由于重新加载了json文件,所之前加载的值就没有,需要针对部分值再加载一次
//Low Cost AC Charge Mode要加载充放电起始时间
-(void)loadCumtomDataWithDevInfo:(NSDictionary *)dic
{
   
    
    //需要加载的值
    NSArray *loadKey = @[@"Inv1_FeedPoUtEn",@"Inv1_PvDisFeNormEn",@"Inv1_PvDisFeLossEn",@"Inv1_PvDisLoNormEn",@"Inv1_PvDisLoLossEn",@"Inv1_StartAcChTim",@"Inv1_StopAcChTim",@"Inv1_SecStartAcChT",@"Inv1_SecStopAcChT",@"Inv1_StaAcChLoadT",@"Inv1_StopAcChLoadT"];
    
    for (DevSettingModel *child_model in self.properList) {
        //日月元 Inverter参数设置  self define mode 以外的其他四种模式不加载默认值
       
        BOOL find = NO;
        for (NSString *key in loadKey) {
            if([child_model.field isEqualToString:key]){
                find = YES;
                break;
            }
            
        }
        if(find == NO) continue;
        if(child_model.disable) continue;
        
        if ([dic[child_model.field] isKindOfClass:[NSString class]]) {
            child_model.content = dic[child_model.field];
        }else{
            if([child_model.field isEqualToString:@"Inv1_PvDisFeNormEn"]){
                
            }
            NSNumber *number = dic[child_model.field];
            if (child_model.ratio) {
                number = @([dic[child_model.field] integerValue]*[child_model.ratio doubleValue]);
            }
            //开关类型,值超过1的情况
            if([child_model.type isEqualToString:@"switch"]&& [number integerValue]>1){
                number = (0);
            }
            NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
            formatter.numberStyle = NSNumberFormatterDecimalStyle;
            //formatter.maximumFractionDigits = 1;
            [formatter setRoundingMode: NSNumberFormatterRoundDown];
            child_model.content = [[formatter stringFromNumber:number] stringByReplacingOccurrencesOfString:@"," withString:@""];
        }

        if([child_model.type isEqualToString:@"select"]){
            child_model.inputModel.content = child_model.content;
            for (DevSettingOptionModel *select_model in child_model.inputModel.optionList) {
                if([child_model.content integerValue] == select_model.textValue){
                    child_model.inputModel.content = select_model.text;
                    child_model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];
                }
            }

        }
    }

    
}

@end
